package com.lzm.ydpt;

import android.app.ProgressDialog;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.byt.framlib.base.BaseActivity;
import com.byt.framlib.basemvp.BasePresenter;
import com.byt.framlib.commonutils.ToastUitl;
import com.example.message.R;
import com.example.message.dto.BaseDto;
import com.example.message.dto.BaseResponseDto;
import com.example.message.http.Api;
import com.example.message.view.ClearEditText;
import com.example.message.vo.UserVo;
import com.hyphenate.EMError;
import com.hyphenate.chat.EMClient;
import com.hyphenate.exceptions.HyphenateException;
import com.lzmpt.imchat.DemoHelper;

import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

public class RegisterActivity extends BaseActivity {
    private static final String TAG = "RegisterActivity";
    private RelativeLayout rlCancel;
    private ClearEditText etUsername;
    private ClearEditText etPwd;
    private RelativeLayout rlEyeOne;
    private ImageView ivEye;
    private ClearEditText etPhone;
    private RelativeLayout rlEyeTwo;
    private LinearLayout llGreed;
    private ImageView ivAgree;
    private TextView tvRegisterUserService;
    private TextView tvPrivet;
    private TextView tvOk;
    private boolean isAgree;

    @Override
    public int getLayoutId() {

        return R.layout.activity_register;
    }

    @Override
    public BasePresenter initPreData() {
        return null;
    }

    private boolean mbDisplayFlg;

    @Override
    public void initView() {
        rlCancel = (RelativeLayout) findViewById(R.id.rl_cancel);
        etUsername = (ClearEditText) findViewById(R.id.et_username);
        etPwd = (ClearEditText) findViewById(R.id.et_pwd);
        rlEyeOne = (RelativeLayout) findViewById(R.id.rl_eye_one);
        ivEye = (ImageView) findViewById(R.id.iv_eye);
        etPhone = (ClearEditText) findViewById(R.id.et_phone);
        rlEyeTwo = (RelativeLayout) findViewById(R.id.rl_eye_two);
        llGreed = (LinearLayout) findViewById(R.id.ll_greed);
        ivAgree = (ImageView) findViewById(R.id.iv_agree);
        tvRegisterUserService = (TextView) findViewById(R.id.tv_register_user_service);
        tvPrivet = (TextView) findViewById(R.id.tv_privet);
        tvOk = (TextView) findViewById(R.id.tv_ok);

        tvOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(etPhone.getText().toString())
                        || TextUtils.isEmpty(etPwd.getText().toString())) {
                    Toast.makeText(getApplicationContext(), "请填写信息完整", Toast.LENGTH_SHORT).show();
                    return;

                }
                if(!isAgree){
                    Toast.makeText(getApplicationContext(), "请勾选用户服务协议", Toast.LENGTH_SHORT).show();
                    return;
                }
                register(etPhone.getText().toString(), etPwd.getText().toString());
            }
        });
        rlEyeOne.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!mbDisplayFlg) {
                    // display password text, for example "123456"
                    etPwd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    ivEye.setImageResource(R.drawable.image_login_open);
                } else {
                    // hide password, display "."
                    etPwd.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    ivEye.setImageResource(R.drawable.image_login_close);
                }
                etPwd.setSelection(etPwd.getText().toString().length());//将光标移至文字末尾
                mbDisplayFlg = !mbDisplayFlg;
                etPwd.postInvalidate();

            }
        });
        ivAgree.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isAgree = !isAgree;
                if (isAgree) {
                    ivAgree.setImageResource(R.drawable.image_checked);
                } else {
                    ivAgree.setImageResource(R.drawable.image_uncheck);
                }
            }
        });


    }

    private void register(final String username, final String pwd) {
        final ProgressDialog pd = new ProgressDialog(this);
        pd.setMessage(getResources().getString(R.string.Is_the_registered));
        pd.show();
        UserVo vo = new UserVo();
        vo.setUsername(username);
        vo.setPhone(username);
        vo.setPassword(pwd);
        Api.newMember(vo).
                subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread()).
                subscribe(new Subscriber<BaseDto<BaseResponseDto>>() {
                    @Override
                    public void onSubscribe(Subscription s) {
                        s.request(100);
                    }

                    @Override
                    public void onNext(BaseDto<BaseResponseDto> baseDto) {
                        pd.dismiss();
                        if (baseDto.getCode()==200) {
                            Log.e(TAG, "onNext: 注册服务器成功" );
                            Toast.makeText(getApplicationContext(), "注册成功", Toast.LENGTH_SHORT).show();
                            finish();
                        } else {
                            Log.e(TAG, "onNext: 注册服务器失败"+baseDto.getMessage() );
                            Toast.makeText(getApplicationContext(), baseDto.getMessage(), Toast.LENGTH_SHORT).show();
                        }


                    }

                    @Override
                    public void onError(Throwable t) {
                        Log.e(TAG, "onNext: 注册服务器失败"+t.getMessage() );
                        Toast.makeText(getApplicationContext(), "注册失败：" + t.getMessage(), Toast.LENGTH_SHORT).show();
                        pd.dismiss();
                    }

                    @Override
                    public void onComplete() {

                    }
                });


//        new Thread(new Runnable() {
//            public void run() {
//                try {
//                    // call method in SDK
//                    EMClient.getInstance().createAccount(username, pwd);
//                    runOnUiThread(new Runnable() {
//                        public void run() {
//                            if (!RegisterActivity.this.isFinishing())
//                                pd.dismiss();
//                            // save current user
//                            DemoHelper.getInstance().setCurrentUserName(username);
//                            Toast.makeText(getApplicationContext(), getResources().getString(R.string.Registered_successfully), Toast.LENGTH_SHORT).show();
//                            finish();
//                        }
//                    });
//                } catch (final HyphenateException e) {
//                    runOnUiThread(new Runnable() {
//                        public void run() {
//                            if (!RegisterActivity.this.isFinishing())
//                                pd.dismiss();
//                            int errorCode=e.getErrorCode();
//                            if(errorCode== EMError.NETWORK_ERROR){
//                                Toast.makeText(getApplicationContext(), getResources().getString(R.string.network_anomalies), Toast.LENGTH_SHORT).show();
//                            }else if(errorCode == EMError.USER_ALREADY_EXIST){
//                                Toast.makeText(getApplicationContext(), getResources().getString(R.string.User_already_exists), Toast.LENGTH_SHORT).show();
//                            }else if(errorCode == EMError.USER_AUTHENTICATION_FAILED){
//                                Toast.makeText(getApplicationContext(), getResources().getString(R.string.registration_failed_without_permission), Toast.LENGTH_SHORT).show();
//                            }else if(errorCode == EMError.USER_ILLEGAL_ARGUMENT){
//                                Toast.makeText(getApplicationContext(), getResources().getString(R.string.illegal_user_name),Toast.LENGTH_SHORT).show();
//                            }else if(errorCode == EMError.EXCEED_SERVICE_LIMIT){
//                                Toast.makeText(RegisterActivity.this, getResources().getString(R.string.register_exceed_service_limit), Toast.LENGTH_SHORT).show();
//                            }else{
//                                Toast.makeText(getApplicationContext(), getResources().getString(R.string.Registration_failed), Toast.LENGTH_SHORT).show();
//                            }
//                        }
//                    });
//                }
//            }
//        }).start();
    }
}
